<template>
  <a-space direction="vertical" style="width: 100%" size="large">
    <!-- Upload component with max count of 1 -->


    <a-upload
        v-model:file-list="fileList"
        list-type="picture"
        :max-count="1"
        action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
        :custom-request="handleCustomRequest"
        :on-change="handleChange"
    >
      <a-button>
        <upload-outlined/>
       请上传图片，复制地址
      </a-button>
    </a-upload>

    <a-button type="primary" @click="submitUpload" v-if="image==''">
      这里是文件路径，请上传文件
    </a-button>
    <a-button type="primary" @click="submitUpload" v-else>
      {{ image }}
    </a-button>
  </a-space>


</template>

<script lang="ts" setup>
import {ref} from 'vue';
import {UploadOutlined} from '@ant-design/icons-vue';
import type {UploadProps, UploadFile} from 'ant-design-vue';
import axios from 'axios';
import myaxios from "../../Axios/myaxios";
import {Modal} from "ant-design-vue";

const image = ref('')
// File list state
const fileList = ref<UploadProps['fileList']>([]);

// Handle the custom request for uploading the file manually
const handleCustomRequest = async (options: any) => {
  if (fileList.value.length > 0) {
    const file = fileList.value[0];
    const formData = new FormData();
    formData.append('mfile', file.originFileObj); // 上传文件

    try {
      const response = await myaxios.post('/photo/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });

      // 上传成功后更新文件状态和 URL
      fileList.value = [
        {
          ...file,
          status: 'done', // 标记为上传成功
        },
      ];
      image.value = response;
      console.log('File uploaded successfully', image.value);
    } catch (error) {
      fileList.value = [
        {
          ...file,
          status: 'error', // 上传失败，设置为 error 状态
        },
      ];
      console.error('Error uploading file', error);
    }
  } else {
    console.error('No file selected');
  }
};

const handleChange: UploadProps['onChange'] = ({fileList: newFileList}) => {
  fileList.value = newFileList;
};
const submitUpload = () => {
  if (image.value !== '') {
    // Copy the image path to clipboard
    navigator.clipboard.writeText(image.value).then(() => {
      Modal.success({
        title: '成功',
        content: '复制成功',
      });
    }).catch(err => {
      console.error('复制失败', err);
    });
  }
};
</script>

